<script lang="ts">
import { useLocale } from '~/modules/locale';

export const cfRules = [{ validator: (_: any, v: string) => formResult(v ? true : $t('hAhflxjXOfxvdFyfXHrRc')) }];

function generateUUID(): string {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}
</script>

<script lang="ts" setup>
const props = defineProps<{ onChange?: (token: string) => void }>();

const valueRef = defineModel<string>('value', { default: void 0 });

const ctx = getCurrentInstance();

const DOM_ID = `turnstile-container-${ctx?.uid || generateUUID() || dayjs().valueOf()}`;

const DEV_SITEKEY = '3x00000000000000000000FF';

const PROD_SITEKEY = '0x4AAAAAAA36Yu3KUILvtKlg';

const appStore = useAppStore();
const { handshake } = storeToRefs(appStore);

!handshake.value && appStore.handshakeQry.refetch();

const getTurnstile = () => (window as any).turnstile;

function setValue(token?: string) {
  props.onChange?.(token ?? '');
  valueRef.value = token ?? '';
}

const widgetIdRef = ref('');

function reset() {
  setValue();
  widgetIdRef.value && getTurnstile()?.reset?.(widgetIdRef.value);
}

function renderTurnstile() {
  const locale = toValue(useLocale().locale).toLowerCase();
  const language = ['ur-pk'].map(x => x.toLowerCase()).includes(locale) ? 'en-us' : locale;
  return getTurnstile()?.render?.(`#${DOM_ID}`, {
    'sitekey': envs.isDevelopment ? DEV_SITEKEY : (handshake.value?.cf_site_key || PROD_SITEKEY),
    'size': 'flexible',
    'theme': 'dark',
    'language': language === 'zh-hk' ? 'zh-tw' : language,
    'retry': 'auto',
    'refresh-expired': 'auto',
    'refresh-timeout': 'auto',
    'retry-interval': 28000,
    'callback': setValue,
    'error-callback': () => setValue(),
    'expired-callback': () => setValue(),
    'unsupported-callback': () => setValue(),
    'timeout-callback': reset,
  }) as string || '';
}

onMounted(async () => {
  if (!handshake.value) {
    await appStore.handshakeQry.refetch();
  }
  getTurnstile()?.ready?.(() => (widgetIdRef.value = renderTurnstile()));
});

defineExpose({ reset });
</script>

<template>
  <div :id="DOM_ID" />
</template>
